<template>
	<view class="container">
		<view class="top-wrapper">
			<CustomNavBar class="title">
				<template v-slot:center>
					<text
						class='title-text'>{{orderDetails.title||'--'}}-{{orderDetails.serviceStatusName||'--'}}</text>
				</template>
				<template v-slot:left>
					<view class="back uni-flex uni-align-center uni-justify-center" @click="goBack">
						<uni-icons type="left" size="20" color="#333333"></uni-icons>
					</view>
				</template>
			</CustomNavBar>
		</view>

		<view class="content">
			<view class="content-top">
				<view class="all-Tobeconfirmed-container">
					<!-- 实际卡片 -->
					<view class="all-Tobeconfirmed">
						<view class="service-time-box">
							<text class='left-text'>订单编号</text>
							<text
								class='right-text'>{{orderDetails.id===null||orderDetails.id===''?'--':orderDetails.id}}</text>
						</view>
						<view class="service-time-box">
							<text class='left-text'>订单日期</text>
							<text
								class='right-text'>{{busOrderServices.length > 0 ? (busOrderServices[0].endTime || '--') : '--'}}</text>
						</view>
						<view class="service-time-box">
							<view class="service-contact">
								<text class='left-text'>联系人</text>
							</view>
							<view class="right-box">
								<text
									class='right-text'>{{servicePosition.name===null||servicePosition.name===''?'--':servicePosition.name}}</text>
								<image :src="`${$ImgBaseUrl}service-detail-phone.png`" class='phone' @click="handleCall"
									:data-phone="servicePosition.phone||''" />
							</view>
						</view>
						<view class="service-time-box">
							<text class='left-text'>服务时间</text>
							<text
								class='right-text'>{{busOrderServices.length > 0 ? (busOrderServices[0].startTime || '--') : '--'}}</text>
						</view>
						<view class="service-time-box">
							<text class='left-text'>服务地址</text>
							<text
								class='right-text'>{{servicePosition.address===null||servicePosition.address===''?'--':servicePosition.address}}</text>
						</view>


						<view class="detail-map">
							<!-- 地图容器 -->
							<map id="map" :latitude="center.latitude" :longitude="center.longitude" :scale="15"
								class="map-container" show-location :enable-scroll="true" :markers="[{
																				      id: index,  // 唯一标识，必填
																				      latitude: Number(servicePosition.lat),
																				      longitude: Number(servicePosition.lng),
																				      width: 35,  // 标记点宽度（rpx）
																				      height: 37,  // 标记点高度（rpx）
																					   iconPath: `${$ImgBaseUrl}positon-icon.png` 
																				    }]" />
						</view>
						<view class="notes-box">
							<text class='left-text'>备注</text>
							<text
								class='right-text'>{{orderDetails.remark===null||orderDetails.remark===''?'-':orderDetails.remark}}</text>
						</view>
					</view>
				</view>
			</view>

			<view class="content-center" v-if="orderDetails.serviceInfo.length>0">
				<view class="service-matter">
					<view class="title-box">
						<text class='title'>服务事项</text>
					</view>
					<view class="line">

					</view>
					<!-- 渲染 -->
					<view class="service-matter-content" v-for="(item,index) in orderDetails.serviceInfo" :key="index">
						<view class="title">
							<image :src="`${$ImgBaseUrl}order-detail-setviceMatter.png`" class='setviceMatter' />
							<text class='title-text'>{{item.itemName}}</text>
						</view>
						<view class="text-box">
							<view class="drop">

							</view>
							<text class='text'>{{item.remark}}</text>
						</view>

					</view>

				</view>
			</view>


		</view>
		<!-- 待确认 待接单 -->
		<view class="content-bottom" v-if="orderDetails.serviceStatus==='SERVICE_WAIT'">
			<button type="default" class='refuse-btn' @click="handleRefuseOrders">拒绝</button>
			<button type="default" class='ReceivingOrders-btn' @click="handleReceivingOrders">接单</button>
		</view>

		<!-- 已接单 未预约 -->
		<view class="content-bottom" v-if="orderDetails.serviceStatus==='SERVICE_RECEIVED'">

			<button type="default" class='reach-btn' @click="handleAppointment">去预约</button>
		</view>
		<!-- 已预约 未到达-->
		<view class="content-bottom" v-if="orderDetails.serviceStatus==='SERVICE_ADVANCE'">
			<!-- <view class="left" @click="goServiceChange">
				<image :src="`${$ImgBaseUrl}service-change.png`" class='service-change'></image>
				<text class='text'>服务变更</text>
			</view> -->
			<button type="default" class='reach-btn' @click="handleReach">到达</button>
		</view>

		<!-- 服务中-->
		<view class="content-bottom" v-if="orderDetails.serviceStatus==='SERVICE_ING'">
			<!-- <view class="left" @click="goServiceChange">
				<image :src="`${$ImgBaseUrl}service-change.png`" class='service-change'></image>
				<text class='text'>服务变更</text>
			</view> -->
			<button type="default" class='reach-btn' @click="handleEnd">结束</button>
		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,

	} from "vue";
	import CustomNavBar from "@/components/custom-navbar/index.vue";
	import {
		orderDetail,
		reachOrder,
		endOrder,
		receiveOrder,
		advanceOrder
	} from "@/api/serviceOrder.js";
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const orderDetails = ref({})
	const servicePosition = ref({})
	const busOrderServices = ref([])
	// 页面加载时获取参数
	onLoad(async (options) => {
		const orderId = options.id; // 假设从路由获取
		if (!orderId) {
			uni.showToast({
				title: "订单ID不能为空",
				icon: "none"
			});
			return;
		}

		try {
			const res = await orderDetail(orderId); // 直接传 orderId
			console.log("订单详情:", res.data);
			if (res.code === 200) {
				orderDetails.value = res.data
				servicePosition.value = res.data.orderAddress
				busOrderServices.value = res.data.busOrderServices
				console.log('busOrderServices[0].endTime', busOrderServices.value);
			}
		} catch (err) {
			uni.showToast({
				title: "获取订单失败",
				icon: "none"
			});
		}
	});
	const handleCall = (e) => {
		// 从事件对象中获取传递的电话号码（data-phone 的值）
		const phoneNumber = e.currentTarget.dataset.phone;

		// 校验：若电话号码为空，提示用户
		if (!phoneNumber || phoneNumber.trim() === '') {
			uni.showToast({
				title: '未获取到联系人电话',
				icon: 'none',
				duration: 1500
			});
			return;
		}

		// 调用uni-app API唤起系统拨号界面
		uni.makePhoneCall({
			phoneNumber: phoneNumber, // 目标电话号码
			success: () => {
				console.log('唤起拨号界面成功');
				// 可选：拨号成功后的逻辑（如记录日志）
			},
			fail: (err) => {
				// 处理失败场景（如用户点击取消拨号）
				if (err.errMsg === 'makePhoneCall:fail cancel') {
					console.log('用户取消拨号');
					// 可选：用户取消时无需提示，避免干扰
				} else {
					// 其他错误（如设备不支持拨号）
					uni.showToast({
						title: '拨号失败，请稍后重试',
						icon: 'none',
						duration: 1500
					});
					console.error('拨号失败:', err);
				}
			}
		});
	};
	// 坐标数据
	const center = ref({
		latitude: '',
		longitude: ''
	});

	const getLocation = async () => {
		try {
			await uni.authorize({
				scope: "scope.userLocation",
				fail: () => {
					uni.showModal({
						title: "提示",
						content: "需要位置权限才能使用地图功能",
						confirmText: "去设置",
						success: (res) => {
							if (res.confirm) uni.openSetting();
						},
					});
					throw new Error("用户拒绝授权");
				},
			});

			const res = await new Promise((resolve, reject) => {
				uni.getLocation({
					type: "gcj02",
					success: resolve,
					fail: reject,
				});
			});

			center.value = {
				latitude: res.latitude,
				longitude: res.longitude,
			};
			console.log('center.value', center.value);
			return res;
		} catch (err) {
			console.warn("获取位置失败:", err);
			return center.value;
		}
	};
	// 点击到达按钮
	const handleReach = () => {
		const params = {
			orderId: orderDetails.value.id
		};
		reachOrder(params).then((res) => {
			console.log('到达接口成功', res);
			if (res.code === 200) {
				uni.showToast({
					title: res.msg
				});
				// 关键：更新为服务中状态（如 SERVICE_ING）
				orderDetails.value.serviceStatus = 'SERVICE_ING';
				orderDetails.value.serviceStatusName = '服务中';
			}
		}).catch(err => {
			console.error('到达接口失败', err);
		});
	};
	// 点击结束按钮
	const handleEnd = () => {
		const params = {
			orderId: orderDetails.value.id
		};
		endOrder(params).then((res) => {
			console.log('结束接口成功', res);
			if (res.code === 200) {
				uni.showToast({
					title: res.msg
				});
				// 关键：更新为服务完成状态（如 SERVICE_END）
				orderDetails.value.serviceStatus = 'SERVICE_END';
				orderDetails.value.serviceStatusName = '服务完成';
				if (orderDetails.value.serviceStatus === 'SERVICE_END') {
					uni.navigateTo({
						url: `/pages/order/ServiceOrder/ServiceOrderDetailComplete?id=${res.data.id}`
					});
				}
			}
		}).catch(err => {
			console.error('结束接口失败', err);
		});
	};
	// 点击接单按钮
	const handleReceivingOrders = () => {
		const params = {
			serviceStatus: 'SERVICE_RECEIVED',
			orderId: orderDetails.value.id
		};
		receiveOrder(params).then((res) => {
			console.log('接单接口成功', res);
			if (res.code === 200) {
				uni.showToast({
					title: res.msg
				});
				// 关键：更新为接单后的状态（如 SERVICE_RECEIVED）
				orderDetails.value.serviceStatus = 'SERVICE_RECEIVED';
				orderDetails.value.serviceStatusName = '已接单';
			}
		}).catch(err => {
			console.error('接单接口失败', err);
		});
	};
	// 点击拒绝接单按钮
	const handleRefuseOrders = (() => {
		const params = {
			serviceStatus: orderDetails.value.serviceStatus,
			orderId: orderDetails.value.id
		}
		// 预约接口调用
		receiveOrder(params).then((res) => {
			console.log('接单接口成功', res);
			// 接口成功后，触发事件通知父组件刷新订单列表
			// emit('refreshOrderList'); // 关键：通知父组件调用ServiceOrderList
			if (res.code === 200) {
				uni.showToast({
					title: res.msg,
				});
			}
		}).catch(err => {
			console.error('接单接口失败', err);
		})
	})
	// 点击去预约按钮
	const handleAppointment = () => {
		const params = {
			orderId: orderDetails.value.id
		};
		advanceOrder(params).then((res) => {
			console.log('预约接口成功', res);
			if (res.code === 200) {
				uni.showToast({
					title: res.msg
				});
				// 关键：更新为已预约状态（如 SERVICE_ADVANCE）
				orderDetails.value.serviceStatus = 'SERVICE_ADVANCE';
				orderDetails.value.serviceStatusName = '已预约';
			}
		}).catch(err => {
			console.error('预约接口失败', err);
		});
	};
	const goBack = () => {
		uni.navigateBack({
			delta: 1,
		});
	};
	// 跳转到服务变更页面
	// const goServiceChange = (() => {
	// 	uni.navigateTo({
	// 		url: '/pages/order/ServiceOrder/ServiceChange'
	// 	})
	// })
	onMounted(async () => {
		const location = await getLocation();
	})
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		flex-direction: column;
		background-color: #f5f5f5;
		box-sizing: border-box;
		min-height: 100vh;

		.top-wrapper {
			background-color: #fff;
			flex-shrink: 0;

			.title {
				.title-text {
					color: #303133;
					font-size: 36rpx;
					font-weight: 500;
					display: inline-block;
					max-width: 300rpx;
					white-space: nowrap;
					text-overflow: ellipsis;
					overflow: hidden;

				}
			}
		}

		.content {
			flex: 1;
			padding: 20rpx;
			box-sizing: border-box;
			// height: 100vh;
			margin-bottom: 20rpx;

			.all-Tobeconfirmed-container {
				position: relative;
				// padding: 20rpx 0;
				margin-bottom: 20rpx;

				// 堆叠样式
				.all-Tobeconfirmed {
					z-index: 3;
					width: 100%;
					height: auto;
					min-height: 689rpx;
					border-radius: 20rpx;
					background-color: #fff;
					padding: 25rpx;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;
					justify-content: space-between;


					.service-time-box {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.left-text {
							font-weight: 400;
							font-size: 30rpx;
							color: #666666;
							width: 200rpx;
							/* 固定左侧宽度（根据设计调整，如“服务地址”四个字足够显示） */
							text-align: left;
							/* 左侧文本左对齐 */
						}

						.right-box {
							width: 140rpx;
							display: flex;
							align-items: center;
							justify-content: space-between;

							.right-text {
								font-weight: 400;
								font-size: 30rpx;
								color: #333333;
								/* 核心：文本溢出控制三属性 */
								white-space: nowrap;
								overflow: hidden;
								text-overflow: ellipsis;
								/* 3. 右侧文本占剩余宽度（flex:1），并限制最小宽度 */
								flex: 1;
								min-width: 0;
								/* 关键：解决 flex 子元素宽度溢出问题（兼容部分浏览器） */
								margin-left: 20rpx;
								/* 可选：增加左右文本间距 */
							}

							.phone {
								width: 38rpx;
								height: 38rpx;
							}
						}

						.right-text {
							font-weight: 400;
							font-size: 30rpx;
							color: #333333;

						}



						.service-contact {
							width: 200rpx;
							display: flex;
							align-items: center;
							justify-content: space-between;


							.left-text {
								font-weight: 400;
								font-size: 30rpx;
								color: #666666;
							}
						}

					}

					.notes-box {
						width: 100%;
						display: flex;
						justify-content: space-between;
						align-items: center;

						.left-text {
							font-weight: 400;
							font-size: 30rpx;
							color: #666666;

						}

						.right-text {
							font-weight: 400;
							font-size: 30rpx;
							color: #333333;

						}
					}

					.detail-map {
						width: 100%;

						// height: 222rpx;
						.map-container {
							width: 100%;
							// height: 100vh;
						}
					}
				}


			}

			.content-center {

				.service-matter {
					width: 100%;
					height: auto;
					// min-height: 873rpx;
					background-color: #fff;
					border-radius: 20rpx;
					padding: 25rpx;
					box-sizing: border-box;

					.title-box {
						height: 70rpx;

						.title {
							font-weight: 500;
							font-size: 34rpx;
							color: #333;
						}
					}

					.line {
						width: 100%;
						border: 1rpx solid #E2E2E2;
						margin-bottom: 20rpx;
					}

					.service-matter-content {
						.title {
							// width: auto;
							display: flex;
							align-items: center;
							// justify-content: space-between;
							margin-bottom: 20rpx;

							.setviceMatter {
								width: 28rpx;
								height: 28rpx;
								margin-right: 20rpx;
							}

							.title-text {
								font-weight: bold;
								font-size: 32rpx;
								color: #333;
							}
						}

						.text-box {
							display: flex;
							// align-items: center;
							margin-left: 40rpx;
							margin-bottom: 20rpx;
							align-items: start;

							.drop {
								margin-right: 10rpx;
								background: #2F80ED;
								width: 13rpx;
								height: 13rpx;
								border-radius: 100%;
								flex-shrink: 0;
								// 2. 禁止压缩：确保宽度不被文本挤压
								flex-grow: 0;
								// 3. （可选）显式锁定尺寸，防止意外继承
								min-width: 13rpx;
								min-height: 13rpx;
								margin-top: 15rpx;
							}

							.text {
								font-weight: 400;
								font-size: 30rpx;
								color: #333;
								line-height: 1.5;
							}
						}
					}
				}
			}
		}

		.content-bottom {
			// width: 100%;
			// max-height: 166rpx;
			height: 166rpx;
			background-color: #fff;
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 0rpx 35rpx;

			// box-sizing: border-box;
			.left {
				display: flex;
				flex-direction: column;
				justify-content: space-between;
				align-items: center;
				height: 80rpx;

				.service-change {
					width: 41rpx;
					height: 41rpx;
				}

				.text {
					color: #999999;
					font-size: 24rpx;
					font-weight: 400;
				}
			}

			.reach-btn {
				height: 88rpx;
				width: 540rpx;
				background: #2F80ED;
				border-radius: 44rpx;
				color: #fff;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 500;
				font-size: 30rpx;
			}

			// 拒绝和接单按钮样式
			.refuse-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 240rpx;
				height: 88rpx;
				border-radius: 44rpx;
				border: 1rpx solid #EB4747;
				font-weight: 500;
				font-size: 30rpx;
				color: #EB4747;
			}

			.ReceivingOrders-btn {
				display: flex;
				align-items: center;
				justify-content: center;
				background: #2F80ED;
				border-radius: 44rpx;
				height: 88rpx;
				width: 410rpx;
				font-weight: 500;
				font-size: 30rpx;
				color: #FFFFFF;
			}
		}
	}
</style>